<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="品牌" prop="brand">
        <el-input
          v-model="queryParams.brand"
          placeholder="请输入品牌"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="联系人" prop="contact">
        <el-select v-model="queryParams.contact" placeholder="请选择当前状态" clearable>
          <el-option
            v-for="user in userList"
            :key="user.id"
            :label="user.username"
            :value="user.username"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="租借人" prop="rentUserId">
        <el-select v-model="queryParams.rentUserId" placeholder="请选择当前状态" clearable>
          <el-option
            v-for="user in userList"
            :key="user.id"
            :label="user.username"
            :value="user.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="出租时间" prop="periodTime">
        <el-date-picker
          v-model="queryParams.periodTime"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="当前状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择当前状态" clearable>
          <el-option
            v-for="dict in dict.type.cr_rent"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['manager:rent:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['manager:rent:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['manager:rent:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="rentList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="租借ID" align="center" prop="id" width="140"/>
      <el-table-column label="品牌" align="center" prop="brand" width="140"/>
      <el-table-column label="联系人" align="center" prop="contact" width="140"/>
      <el-table-column label="联系人电话" align="center" prop="contactPhone" width="140"/>
      <el-table-column label="租借人" align="center" prop="rentUsername" width="140"/>
      <el-table-column label="租借人电话" align="center" prop="rentPhone" width="140"/>
      <el-table-column label="出租时间" align="center">
        <template slot-scope="scope">
          {{ scope.row.startTime }} - {{ scope.row.endTime }}
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" width="150">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.cr_rent" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['manager:rent:edit']"
          >修改</el-button> -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['manager:rent:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改租借管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body :style="{height:'530px'}">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <!-- 展示的是品牌，但是传值的是carId -->
        <el-form-item label="品牌" prop="carId">
          <el-select v-model="form.carId" placeholder="请选择车牌号">
            <el-option
              v-for="dict in carIsNotRentList"
              :key="dict.id"
              :label="dict.brand"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="租借人" prop="rentUserId">
          <el-select v-model="form.rentUserId" placeholder="请选择租借人">
            <el-option
              v-for="dict in userList"
              :key="dict.id"
              :label="dict.username"  
              :value="dict.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="当前状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择当前状态">
            <el-option
              v-for="dict in dict.type.cr_rent"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开始出租时间" prop="startTime">
            <el-date-picker
              v-model="form.startTime"
              type="datetime"
              placeholder="选择日期时间"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              @change="startTimeChange"
            />
        </el-form-item>
        <el-form-item label="结束出租时间" prop="endTime">
          <el-date-picker
              v-model="form.endTime"
              type="datetime"
              placeholder="选择日期时间"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              :picker-options="pickerOptions"
            />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listRent, getRent, delRent, addRent, updateRent } from "@/api/manager/rent";
import { listUser } from "@/api/manager/user";
import { listCar, listCarIsNotRent } from "@/api/manager/car";

export default {
  name: "Rent",
  dicts: ['cr_rent'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 租借管理表格数据
      rentList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        carId: null,
        contact: null,
        startTime: null,
        endTime: null,
        periodTime: null,
        status: null,
        brand: null,
        rentUserId: null,
      },
      // 表单参数
      form: {},
      userList: [],
      carList: [],
      carIsNotRentList: [],
      // 表单校验
      rules: {
        carId: [
          { required: true, message: "车牌号不能为空", trigger: "blur" }
        ],
        rentUserId: [
          { required: true, message: "租借人不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "当前状态不能为空", trigger: "blur" }
        ],
        startTime: [
          { required: true, message: "开始时间不能为空", trigger: "blur" }
        ],
        endTime: [
          { required: true, message: "结束时间不能为空", trigger: "blur" }
        ],
      },
      pickerOptions:{
        // 限制日期
        disabledDate: this.disabledDate
      },
    };
  },
  created() {
    this.getList();
    this.getUserList();
    this.getCarIsNotRentList();
  },
  methods: {
    /** 查询租借管理列表 */
    getList() {
      this.loading = true;
      if(this.queryParams && this.queryParams.periodTime){
        let dateStart = new Date(this.queryParams.periodTime[0])
        let yearStart = dateStart.getFullYear()
        let monthStart = String(dateStart.getMonth() + 1).padStart(2, '0');
        let dayStart = String(dateStart.getDate()).padStart(2, '0');
        let dateEnd = new Date(this.queryParams.periodTime[1])
        let yearEnd = dateEnd.getFullYear()
        let monthEnd = String(dateEnd.getMonth() + 1).padStart(2, '0');
        let dayEnd = String(dateEnd.getDate()).padStart(2, '0');
        this.queryParams.startTime = `${yearStart}-${monthStart}-${dayStart}`
        this.queryParams.endTime = `${yearEnd}-${monthEnd}-${dayEnd}`
      }
      console.log(this.queryParams);
      listRent(this.queryParams).then(response => {
        this.rentList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 获取用户列表
    getUserList() {
      listUser().then(response => {
        this.userList = response.rows;
      });
    },
    // 获取车辆列表
    getCarList() {
      listCar().then(response => {
        this.carList = response.rows;
      });
    },
    // 获取未出租的车辆列表
    getCarIsNotRentList() {
      listCarIsNotRent().then(response => {
        console.log(response.rows);
        this.carIsNotRentList = response.rows;
      });
    },
    // 
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        carId: null,
        brand: null,
        contact: null,
        contactPhone: null,
        rentUserId: null,
        status: null,
        startTime: null,
        endTime: null,
        status: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        periodTime: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams = {
        carId: null,
        contact: null,
        startTime: null,
        endTime: null,
        periodTime: null,
        status: null,
        brand: null,
        rentUserId: null,
      }
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加租借管理";
      this.getCarIsNotRentList();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getRent(id).then(response => {
        console.log(response.data);
        this.form = response.data;
        this.open = true;
        this.title = "修改租借管理";
        this.getCarIsNotRentList();
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateRent(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addRent(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id;
      this.$modal.confirm('是否确认删除租借管理编号为"' + id + '"的数据项？').then(function() {
        return delRent(id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('manager/rent/export', {
        ...this.queryParams
      }, `rent_${new Date().getTime()}.xlsx`)
    },
    // 禁止选择空闲时间开始及之前的日期
    disabledDate(time) {
      if(this.form.startTime){
        // 设置空闲时间范围为七天
        return time.getTime() < new Date(this.form.startTime) 
        || time.getTime() > new Date(new Date(this.form.startTime).getTime() + 7 * 24 * 60 * 60 * 1000);
      }
    },
    // 监听空闲时间开始时间变化
    startTimeChange(){
      if(this.form.endTime && (this.form.endTime <= this.form.startTime || this.form.endTime.getTime() > new Date(new Date(this.form.startTime).getTime() + 7 * 24 * 60 * 60 * 1000).getTime())){
        this.form.endTime = new Date(new Date(this.form.startTime).getTime() + 24 * 60 * 60 * 1000)
      }
    }
  }
};
</script>
